package org.jfunction.ui.model;

import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
import org.jfunction.JFunctionFile;
import org.jfunction.JFunctionFileParser;

public class UIModel implements IDocumentListener {
	
	private final JFunctionFileParser parser = new JFunctionFileParser();
	private boolean staleText;
	private boolean staleModel;
	private IDocument document;
	private JFunctionFile jf;
	
	public UIModel(IDocument document) {
		this.document = document;
		document.addDocumentListener(this);
	}
	
	@Override
	public void documentAboutToBeChanged(DocumentEvent event) {
	}
	
	@Override
	public void documentChanged(DocumentEvent event) {
		staleModel = true;
	}
	
	public JFunctionFile get() {
		if (jf == null || staleModel) {
			jf = parser.parseText(document.get());
			staleModel = false;
		}
		return jf;
	}
	
	public void synchDocument() {
		if (staleText) {
			JFunctionFile documentsJF = parser.parseText(document.get());
			staleText = false;
		}
	}
}
